package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/*
			  ________   ___   ___        ___   ________   ___   ___        ___
	 ________|\   __  \_|\  \_|\  \______|\  \_|\   __  \_|\  \_|\  \______|\  \_________
	 \       \ \  \_\ /_\ \  \\ \  \     \ \  \\ \  \_\ /_\ \  \\ \  \     \ \  \        \
	  \       \ \   __  \\ \  \\ \  \     \ \  \\ \   __  \\ \  \\ \  \     \ \  \        \
	   \       \ \  \_\  \\ \  \\ \  \____ \ \  \\ \  \_\  \\ \  \\ \  \____ \ \  \        \
	    \       \ \_______\\ \__\\ \_______\\ \__\\ \_______\\ \__\\ \_______\\ \__\        \
	     \       \|_______| \|__| \|_______| \|__| \|_______| \|__| \|_______| \|__|         \
	 	  \___________________________________________________________________________________\

+------------+
|2020/4/18   |
|11:58       |
+------------+
*/
@Component
public class SpringSecurityUserService implements UserDetailsService {
    @Reference
    private UserService userService;

    //根据用户名查询信息
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    //远程调用用户服务，根据用户名查询用户信息
        User user = userService.findByUsername(username);
        if (user == null) {
            //用户名不存在
            return null;
        }
        List<GrantedAuthority> list = new ArrayList<>();
        //取得user所具有的角色
        Set<Role> roles = user.getRoles();
        //遍历角色
        for (Role role : roles) {
            list.add(new SimpleGrantedAuthority(role.getKeyword()));
            //获取角色权限
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        UserDetails userDetails = new org.springframework.security.core.userdetails.User(username,user.getPassword(),list);
        return userDetails;
    }
}
